package edu.johnpank.libassistant.util

import edu.johnpank.libassistant.entity.User
import edu.johnpank.libassistant.services.UserService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import org.springframework.validation.Errors
import org.springframework.validation.Validator

@Component
class UserValidator(
    @Autowired
    val userService: UserService
): Validator{
    override fun supports(clazz: Class<*>): Boolean {
        return User::class == clazz
    }

    override fun validate(target: Any, errors: Errors) {
        val user = target as User
        if (user.login.let { userService.getUserByLogin(it).isEmpty }){
            return
        }else{
            errors.rejectValue("login", "User_with_this_login_is_exist")
        }
    }
}
